package com.example.fresheveryday.restful;


import com.example.fresheveryday.exception.ServiceException;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.util.HashMap;
import java.util.Map;

@Data
public class JsonResult<T> {
    /*系统发生异常时的默认提示信息*/
    private static String ERROR_MSG = "系统异常，请稍后重试...";

    @ApiModelProperty(value = "响应状态码", position = 1, example = "200, 400, 401, 403, 404, 406, 409, 500")
    private Integer code; // 状态码

    @ApiModelProperty(value = "提示信息", position = 2, example = "登录失败！密码错误！")
    private String msg; // 提示信息

    @ApiModelProperty(value = "响应数据", position = 3)
    private T data; // 数据

    public static JsonResult<Void> success() {
        return success(null);
    }

    public static JsonResult<Void> success(String msg) {
        return success(msg, null);
    }

    public static <T> JsonResult<T> success(String msg, T data) {
        JsonResult<T> jsonResult = new JsonResult<>();

        jsonResult.setCode(ResponseCode.SUCCESS.getValue());
        jsonResult.setMsg(msg);
        jsonResult.setData(data);

        return jsonResult;
    }

    public static JsonResult<Void> error(String msg) {
        JsonResult<Void> jsonResult = new JsonResult<>();

        jsonResult.setCode(ResponseCode.ERROR.getValue());
        jsonResult.setMsg(msg);

        return jsonResult;
    }

    public static JsonResult<Void> error(ServiceException e) {
        return error(e.getResponseCode(), e);
    }

    public static JsonResult<Void> error(ResponseCode responseCode, Throwable e) {
        return error(responseCode, e.getMessage());
    }

    public static JsonResult<Void> error(ResponseCode responseCode, String msg) {
        JsonResult<Void> jsonResult = new JsonResult<>();

        jsonResult.setCode(responseCode.getValue());
        jsonResult.setMsg(msg);

        return jsonResult;
    }

    public static Map<String, Object> returnResultMap(int total, Object rows) {
        Map<String, Object> resultMap = new HashMap<>();

        resultMap.put("total", total);
        resultMap.put("rows", rows);

        return resultMap;
    }

}